<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/10/12 weixinddddd
 * Time: 8:29
 */

namespace app\mobile\controller;

/**
 * Class Weixin
 * @package app\store\controller
 * 处理微信消息回复类
 */
vendor('zoujingli.wechat-php-sdk.include');
class Weixin
{

    /**
     * 接收微信 发来的消息
     */
    public function index(){
        $wechat = & \Wechat\Loader::get_instance('Receive', $this->getWeixiConfig());
        $wechat->valid();//接口验证
        $wechat->getRev();//获取微信发送的内容
        $type = $wechat->getRevType();
        switch($type){
            case 'text'://文本消息
                $this->reply($wechat,$wechat->getRevContent());
                break;
            case 'event'://事件消息
                $this->replyEvent($wechat,$wechat->getRevEvent());
                break;
            case 'image'://图片消息
                $this->replyPic($wechat,$wechat->getRevPic());
                break;
            default :
                $this->reply($wechat);
                break;
        }

    }

    /**
     * @param $obj
     * @param string $info
     * 获取图片消息并下载图片到本地
     */
    private function replyPic($obj,$info=''){
        if($info){
            $mediaid = $info['mediaid'];
            $media = & \Wechat\Loader::get_instance('Media', $this->getWeixiConfig());
            $result = $media->getMedia($mediaid);
            $path = './uploads/album/'.date("Ymd").'/';
            if (!file_exists($path)) {
                mkdir($path, 0777,true);
            }
            $url = $path . date("YmdHis").codestr(6,1) . ".jpg";
            file_put_contents($url,$result);
            $url = 'http://'.config('url_domain_root').ltrim($url,'.');
            //if($aid = cache($obj->getRevFrom())){
            $this->updateAlbum($obj,$url);//修改相册
            //}else{
            //   $this->createAlbum($obj,$url);//创建相册
            // }
        }else{
            $obj->text('欢迎关注公众号')->reply();
        }
    }
    /**
     * 普通文本消息回复  根据接收的内容进行回复
     */
    private function reply($obj,$content=''){
        if($content){
            $info = $this->getKeyword($content);
            if($info){
                $this->replyMsg($obj,$info);
            }else{
                $obj->kefuservice()->reply();//转接到多客服
                //$obj->text('欢迎关注公众号')->reply();//未找到相关 关键词时的回复 （通知微信不做任何处理）
            }
        }else{
            $obj->kefuservice()->reply();//转接到多客服
            //$obj->text('欢迎关注公众号')->reply();
        }

    }

    /**
     * @param $event
     * 事件消息回复
     */
    private function replyEvent($obj,$event){
        if($event['event'] == 'CLICK'){
            //自定义菜单事件处理 根据eventkey查询对应的回复数据
            if($event['key'] == 'myalbum'){
                $uid = $this->addWeixinUser($obj->getRevFrom());
                $info = [
                    'Title' => '我的相册',
                    'PicUrl' => 'http://'.config('url_domain_root').'/static/mobile/images/myalbum.jpg',
                    'Description' => '我的音乐相册',
                    'Url' => 'http://'.config('domain.mobile').'/album/myalbum.html?uid='.$uid
                ];
                $obj->news([$info])->reply();
            }else{
                $info = $this->getEventReply(3,$event['key']);
                if($info){
                    $this->replyMsg($obj,$info);
                }else{
                    $obj->kefuservice()->reply();//转接到多客服
                   // $obj->text('欢迎关注公众号')->reply();
                }
            }

        }elseif($event['event'] == 'subscribe'){
            //关注回复事件
            $info = $this->getEventReply();
            if($info){
                $this->replyMsg($obj,$info);
            }else{
               // $obj->kefuservice()->reply();//转接到多客服
                $obj->text('欢迎关注公众号')->reply();
            }
        }elseif($event['event'] == 'pic_photo_or_album'){
            if($event['key'] == 'createalbum'){
                $this->createAlbum($obj);
            }
        }else{
            //$obj->kefuservice()->reply();//转接到多客服
            $obj->text('欢迎关注公众号')->reply();
        }
    }

    /**
     * @param int $type 2为关注回复 3为菜单自定义事件回复
     * @param string $key $type 为2时才需要传值
     * @return array|false|\PDOStatement|string|\think\Model
     */
    private function getEventReply($type=2,$key=''){
        $map['event_type'] = $type;
        !empty($key) && $map['keyword'] = $key;
        $info = model('weixin_msg_replay')->where($map)->find();
        return $info;
    }
    /**
     * @param $content
     * @return array|false|\PDOStatement|string|\think\Model
     * 根据关键词查询回复内容
     */
    private function getKeyword($content){
        $map['name'] = ['neq',''];
        $list = model('tags')->where($map)->select();
        $reply = [];
        if($list){
            $aid_arr = [];
            foreach($list as $v){
                if(preg_match('/'.$v['name'].'/',$content)){
                    $aid_arr[$v['aid']] = $v['aid'];
                }
            }
            if($aid_arr){
                $reply = model('weixin_msg_replay')->where(['id'=>['in',$aid_arr],'event_type'=>1])->order('ordid desc')->find();
            }
        }
        return $reply;
    }

    /**
     * @param $obj
     * @param $info
     * 回复消息
     */
    private function replyMsg($obj,$info){
        switch($info['type']){
            case 1:
                $obj->text($info['data'])->reply();
                break;
            case 2:
                $obj->news([$info['data']])->reply();
                break;
            case 3:
                $obj->news(array_values($info['data']))->reply();
                break;
            default :
                $obj->text('')->reply();
                break;
        }
    }

    /**
     * @param $obj
     * @param $url
     * 创建或更新相册
     */
    private function createAlbum($obj,$url=''){
        $openid = $obj->getRevFrom();
        $userinfo = $this->addWeixinUser($openid,$obj,true);
        //创建新相册
        $mod = model('weixinalbum');
        $data['uid']   = $userinfo['id'];
        $data['title'] = $userinfo['nickname'].'的相册';
        $data['openid'] = $openid;
        $data['c_id']   = 0;
        $data['tpl']    = 'style3';
        $data['music']  = 2;
        $data['img']    = $url;
        $data['create_time'] = time();
        $mod->save($data);
        $aid = $mod->id;
        if($url){
            $pic_data['url'] = $url;
            $pic_data['aid'] = $aid;
            $pic_data['openid'] = $openid;
            model('weixinalbum_pic')->save($pic_data);
            $text = "<a href='".'http://'.config('domain.mobile')."/album/index.html?do=edit&uid=".$data['uid']."&id=".base64_encode($aid)."'>已收到1张图片，点这里开始制作</a>";
            $obj->text($text)->reply();
        }
        cache($openid,$aid,600);
    }

    /**
     * @param $obj
     * 更新相册
     */
    private function updateAlbum($obj,$url=''){
        $openid = $obj->getRevFrom();
        if($aid = cache($openid)){
            //更新相册
            $uid = $this->addWeixinUser($openid,$obj);
            $mod = model('weixinalbum_pic');
            $data['url'] = $url;
            $data['aid'] = $aid;
            $data['openid'] = $openid;
            $mod->save($data);
            $album_obj = model('weixinalbum');
            $album_img = $album_obj->where(['id'=>$aid])->value('img');
            if(empty($album_img)){
                $album_obj->save(['img'=>$url],['id'=>$aid]);
            }
            $count = $mod->where(['openid'=>$openid,'aid'=>$aid])->count('id');
            $text = "<a href='".'http://'.config('domain.mobile')."/album/index.html?do=edit&uid=".$uid."&id=".base64_encode($aid)."'>已收到{$count}张图片，点这里开始制作</a>";
            $obj->text($text)->reply();
        }else{
            $this->createAlbum($obj,$url);
        }


    }
    private function getWeixiConfig(){
        //$config = config('weixin');
      return getWeixinConfig();
    }

    /**
     * 添加会员
     */
    private function addWeixinUser($openid,$obj='',$all=''){
        $map['weixin_openid'] = $openid;
        //判断会员是否存在
        $user_mod = db('user');
        $user_info = $user_mod->where($map)->field('nickname,id')->find();
        $user_id = $user_info['id'];
        if(!$user_info){
            //添加会员 获取用户信息
            $data['username']      = '微相册用户';
            $data['nickname']      = '微相册用户';
            if(is_object($obj)){
                $weixinuser = $obj->getUserinfo();//获取用户信息
                if($weixinuser){
                    $data['username'] = $data['nickname'] = $weixinuser['nickname'];
                    $weixinuser['headimgurl'] && $data['headimgurl'] = $weixinuser['headimgurl'];
                    $info['address'] = $weixinuser['province'].$weixinuser['city'];
                    $info['sex']     = $weixinuser['sex'] == 1 ? '男' : ($weixinuser['sex'] == 2 ? '女' : '保密');
                }
            }
            $data['c_id'] = 0;
            $data['weixin_openid'] = $openid;
            $data['reg_time']      = time();
            $data['password']      = '';
            $user_mod->insert($data);
            $info['uid'] = $user_mod->getLastInsID();
            db('user_info')->insert($info);
            return $all ? ['id'=>$info['uid'],'nickname'=>$data['nickname']] : $info['uid'];
        }else{
            return $all ? $user_info : $user_id;
        }
    }
}